# -*- coding: UTF-8 -*-

import pandas as pd
from datetime import datetime
from config import config
import numpy as np
import pymongo

from dash_lib.mongodb_helper import get_email_tipper_list_from_online


def trans_date(kickoff):
    # format_kickoff= datetime.strptime(kickoff, '%d %b %Y, %H:%M').time()
    try:
        format_kickoff = datetime.strptime(kickoff, '%d %b %Y, %H:%M').strftime('%Y-%m-%d')
    except TypeError:
        format_kickoff = '2000-01-11'

    return format_kickoff


def indexDay(df):
    pivot_table = pd.pivot_table(df, values=['profit', ], index=['kickoff', 'sport'], columns=['stake', 'pick_type'],
                                 aggfunc={'profit': 'mean'}, fill_value=0, margins=True)
    print(pivot_table)


def analyse_base(df):
    pivot_table = pd.pivot_table(df, values=['profit', 'stake'], index=['kickoff'],
                                 aggfunc={'profit': 'sum', 'stake': 'sum'}, fill_value=0, margins=False)
    cumsum_df = pivot_table.cumsum()
    print_day_duration(df, len(cumsum_df['stake']))
    return cumsum_df


def print_day_duration(df, days_count):
    print('DAY:   %s ==> %s     (days:%s ,count:%d)' %
          (df['kickoff'].min(), df['kickoff'].max(), days_count, len(df['kickoff'])))


def show_yield(cumsum_df):
    stake__max = int(cumsum_df['stake'].max())
    len_of_stake_max = len(str(stake__max))
    inter_value = 1
    n = 0
    while n < len_of_stake_max:
        inter_value *= 10
        n += 1
    # print( len_of_stake_max, inter_value
    # print('========  show yield     ========'
    cumsum_df['yield'] = cumsum_df['profit'] / cumsum_df['stake'] * inter_value
    cumsum_df['yield'] = cumsum_df['yield'].apply(
        lambda x: x if (0.5 > x / inter_value > -0.3) else (
            inter_value * 0.5 if (x / inter_value > 0.5) else inter_value * -0.2))
    return cumsum_df


def filter_df(df, query_array):
    filtered_df = df
    if query_array:
        for item in query_array:
            filtered_df = filtered_df.query(item)
    return filtered_df


def analyse(df):
    base = analyse_base(df)
    base['days'] = base.index.get_level_values('kickoff')
    base['yields'] = base['profit'] / base['stake'] * 100
    base['yields'] = base['yields'].apply(lambda x: 40 if x > 40 else (-33 if x < -33 else x))

    return round_df(base)


def init_config():
    pd.options.display.float_format = '{:,.1f}'.format
    pd.set_option('display.height', 1000)
    pd.set_option('display.max_rows', 500)
    pd.set_option('display.max_columns', 700)
    pd.set_option('display.width', 1000)
    pd.options.mode.chained_assignment = None  # default='warn'

    client = pymongo.MongoClient("mongodb://fyf:qwe@localhost:27017", connect=False)
    return client["test"]


def get_tipper_list(is_only_email=False):
    total_data_frame = pd.DataFrame(list(origin_db.pick.find()))
    tipper_list = total_data_frame['tipper'].unique()
    if is_only_email:
        tipper_list = list(filter(lambda x: x in get_email_tipper_list_from_online(), tipper_list))
    return tipper_list


def get_lastest_granded_pick(blog_name):
    lastpicks = list(origin_db.pick.find({'tipper': blog_name}).sort('last_update', pymongo.DESCENDING).limit(1))
    return lastpicks[0] if lastpicks else None


def init(blog_name):
    print('start analyse :', blog_name)
    data_frame = pd.DataFrame(list(origin_db.pick.find({'tipper': blog_name})))
    del data_frame["_id"]
    data_frame = data_frame.query('profit/stake<=5')
    return round_df(data_frame)


def round_df(df):
    return df.round(2)


origin_db = init_config()
